package com.example.nacos;


import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
public class SFTPExample {
    public static void main(String[] args) {
        String sftpHost = "192.168.88.155";
        int sftpPort = 22; // 默认SSH端口
        String sftpUser = "ftp01";
        String sftpPassword = "ftp01";
        String downloadFile = "/home/ftp01/1.txt";
        String downloadLocalPath = "D:\\log\\1.txt";

        Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(sftpUser, sftpHost, sftpPort);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(sftpPassword);
            session.connect();

            channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp) channel;

            // 下载文件
            channelSftp.get(downloadFile, downloadLocalPath);

            channelSftp.put(downloadLocalPath, "/home/ftp01/2.txt");
            System.out.println("File downloaded successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (channelSftp != null) {
                channelSftp.exit();
            }
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }
}
